package com.car.action.admin;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.alibaba.fastjson.JSONObject;
import com.car.common.model.Area;
import com.car.common.model.Card;
import com.car.common.model.CardDiscuss;
import com.car.common.model.MessageUnreadNum;
import com.car.common.model.NavyUsers;
import com.car.common.model.RemindMessage;
import com.car.common.model.Tags;
import com.car.common.model.TempWrap;
import com.car.common.model.Topics;
import com.car.common.model.UserAlbums;
import com.car.common.model.UserBlack;
import com.car.common.model.UserCheck;
import com.car.common.model.UserFans;
import com.car.common.model.UserHellos;
import com.car.common.model.UserSees;
import com.car.common.model.Users;
import com.car.common.model.UsersInfo;
import com.car.common.model.VipPackage;
import com.car.common.model.VipRecord;
import com.car.intercept.AdminInterceptor;
import com.car.job.TheadImgCheck;
import com.car.tx.OrderService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.ehcache.IDataLoader;
import com.jfinal.template.stat.ast.SetLocal;
import com.utils.APIJSON;
import com.utils.CookiesUtil;
import com.utils.DateUtil;
import com.utils.PicUtil;
import com.utils.RongCloudUtil;
import com.utils.StringUtil;
import com.utils.SystemClock;
import com.utils.Toolkit;


@Before(AdminInterceptor.class)
public class UsersController extends Controller {
	
	private int beishu = 1;
	
	public void online_rand() {
		// and login_status != 0
		String andSql = "select id from users as u where is_true > 1  ";
		if(!StringUtil.empty(getPara("sex"))) {
        	andSql += " and u.sex = " + getPara("sex");
        }
        if(!StringUtil.empty(getPara("area"))) {
        	andSql += " and u.area_id = " + getPara("area");
        }
        if(!StringUtil.empty(getPara("is_true"))) {
        	andSql += " and u.is_true = " + getPara("is_true");
        }
        int limit = 1000/ beishu;
        List<Users> users = Users.dao.find(andSql + " order by rand() limit " + limit);
        for(Users one : users) {
        	Db.update("update users set login_status = 0,logout_time = "+ (SystemClock.now()/1000L + 5 * 6 * 60L + new Random().nextInt(500)* 3 *6L ) +"  where id = " + one.getId());
        }
        renderText("操作成功!");
	}
	
	public void embrace() {
		int user_id = getParaToInt("user_id"); 
		int to_user_id = getParaToInt("to_user_id");
		Users me = Users.dao.findById(user_id);
		UserSees one1 = new UserSees();
		one1.setUserId(user_id);
		one1.setTargetUserId(to_user_id);
		one1.setCreateTime(SystemClock.now()/1000L - 1 * 60);
		one1.setUpdateTime(SystemClock.now()/1000L);
		if (one1.save()) {
			new CardController().giveABPoint(user_id);
			MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_SEE, to_user_id);
		}
		
		VipRecord recordYou = new VipRecord();
		recordYou.setUserId(Integer.valueOf(to_user_id));
		recordYou.setTargetUserId(user_id);
		recordYou.setOrderNum(Toolkit.newTradeNo());
		recordYou.setTitle("被拥抱1℃");
		recordYou.setBuyType("User");
		recordYou.setHot(1);
		recordYou.setStatus(1);
		recordYou.setOrderType(5);
		recordYou.setCreateTime(SystemClock.now()/1000L);
		recordYou.setUpdateTime(SystemClock.now()/1000L);
		recordYou.save();
		Db.update("update users set free_hot = free_hot + 1 where id= "+ to_user_id);
		
	    String content = StringUtil.decode(me.getNickName()) + "(ID:" + (20000000 + user_id)+ ")拥抱了你1℃";
		RongCloudUtil.sendTxt("141", String.valueOf(to_user_id), content);
		
		RemindMessage.dao.save_one(1, 0, user_id, to_user_id);
		renderText("操作成功!");
	}
	public void online() {
		
		String[] ids = getPara("ids").split(",");
 		for(String user_id :ids) {
 			Db.update("update users set login_status = 0,logout_time = "+ (SystemClock.now()/1000L + 5 * 6 * 60L + new Random().nextInt(5)* 30 *60L ) +"  where id = " + user_id);
 		}		
		renderText("操作成功!");
	}
	
	public void online_1() {
		String andSql = "select id from users as u where is_true = 1 and login_status != 0 and sex = 1 and up_time <  " + (SystemClock.now()/1000L - 6*30*24*3600L);
        int limit = 1000/ beishu;
        List<Users> users = Users.dao.find(andSql + " order by rand() limit " + limit);
        for(Users one : users) {
        	long time = (5+ new Random().nextInt(20)) *6*60L;
        	Db.update("update users set login_status = 0,logout_time = "+ (SystemClock.now()/1000L + time ) +"  where id = " + one.getId());
        }
        renderText("操作成功!");
	}
	
	public void online_2() {
		String andSql = "select id from users as u where is_true = 1 and login_status != 0 and sex = 2 and up_time <  " + (SystemClock.now()/1000L - 30*24*3600L);
        int limit = 100/ beishu;
        List<Users> users = Users.dao.find(andSql + " order by rand() limit " + limit);
        for(Users one : users) {
        	long time = (5+ new Random().nextInt(20)) *6*60L;
        	Db.update("update users set login_status = 0,logout_time = "+ (SystemClock.now()/1000L + time ) +"  where id = " + one.getId());
        }
        renderText("操作成功!");
	}
	
	
	public void cancel_gps() {
		Db.update("update users_info set lat = null ,lng = null where user_id = " + getPara("user_id"));
		renderText("操作成功!");
	}
	
	public void cancel_fans() {
		String user_id = getPara("user_id");
		List<UserFans> fans = UserFans.dao.find("select f.*  from user_fans as f left join users as u on f.user_id = u.id where u.is_true > 1 and  f.target_user_id = " + user_id);
		for(UserFans one : fans){
			UserSees one1 = new UserSees();
			one1.setUserId(one.getUserId());
			one1.setTargetUserId(Integer.valueOf(user_id));
			one1.setCreateTime(SystemClock.now()/1000L);
			one1.setUpdateTime(SystemClock.now()/1000L);
			if (one1.save()) {
				new CardController().giveABPoint(one.getUserId());
				Db.delete("delete from user_fans where id = " + one.getId());
				MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_SEE, Integer.valueOf(user_id));
			}
		}
		int fansCnt = fans == null ? 0 : fans.size();
		renderText("取消了"+fansCnt+"关注");
				
	}
	
	public void black() {
		Long user_id = getParaToLong("user_id");
        UserBlack one = UserBlack.dao.findFirst("select id,status,user_id,black_user_id from user_black where user_id = " + user_id + " and black_user_id = " + getPara("black_user_id"));
        if (one == null) {
        	int target_user_id = getParaToInt("black_user_id");
        	UserSees one1 = new UserSees();
 			one1.setUserId(user_id.intValue());
 			one1.setTargetUserId(target_user_id);
 			one1.setCreateTime(SystemClock.now()/1000L - 1 * 60);
 			one1.setUpdateTime(SystemClock.now()/1000L);
 			if (one1.save()) {
 				new CardController().giveABPoint(user_id.intValue());
 				MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_SEE, target_user_id);
 			}
 			
        	one = new UserBlack();
        	one.set("user_id", user_id);
        	one.set("black_user_id", getPara("black_user_id"));
        	one.set("status", 1);
        	one.set("create_time", SystemClock.now()/1000L);
        	if (one.save()) {
        		Map<String,String> params = Maps.newHashMap();
	        	params.put("userId", String.valueOf(user_id));
	        	params.put("blackUserId", getPara("black_user_id"));
	        	RongCloudUtil.post("http://api-cn.ronghub.com/user/blacklist/add.json", params);
        	}
        } else {
        	if (one.getStatus() == 1) {
        		Db.update("update user_black set status = 2 where id = " + one.getId());
        		Map<String,String> params = Maps.newHashMap();
	        	params.put("userId", String.valueOf(user_id));
	        	params.put("blackUserId", getPara("black_user_id"));
	        	RongCloudUtil.post("http://api-cn.ronghub.com/user/blacklist/remove.json", params);
	        	renderText("已取消拉黑,操作成功!");
        	} else {
        		Db.update("update user_black set status = 1 where id = " + one.getId());
        		Map<String,String> params = Maps.newHashMap();
	        	params.put("userId", String.valueOf(user_id));
	        	params.put("blackUserId", getPara("black_user_id"));
	        	RongCloudUtil.post("http://api-cn.ronghub.com/user/blacklist/add.json", params);
        	}
        }
        renderText("操作成功!");
	}
	
	
	
	public void white() {
		Long user_id = getParaToLong("user_id");
        Map<String,String> params = Maps.newHashMap();
    	params.put("userId", String.valueOf(user_id));
    	params.put("blackUserId", getPara("black_user_id"));
    	RongCloudUtil.post("http://api-cn.ronghub.com/user/blacklist/remove.json", params);
    	
    	params.clear();
    	params.put("userId", getPara("black_user_id"));
    	params.put("blackUserId", String.valueOf(user_id));
    	RongCloudUtil.post("http://api-cn.ronghub.com/user/blacklist/remove.json", params);
    	renderText("已取消拉黑,操作成功!");
	
	}

	public void see() {
		int user_id = getParaToInt("user_id");
		int target_user_id = getParaToInt("target_user_id");
		UserSees one1 = UserSees.dao.findFirst("select * from user_sees where user_id = " + user_id +" and target_user_id =" + target_user_id);
		if (one1 == null) {
			one1 = new UserSees();
			one1.setUserId(user_id);
			one1.setTargetUserId(target_user_id);
			one1.setCreateTime(SystemClock.now()/1000L);
			one1.setUpdateTime(SystemClock.now()/1000L);
			if (one1.save()) {
				new CardController().giveABPoint(user_id);
				MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_SEE, target_user_id);
			}
			UserFans one = new UserFans();
			one.setUserId(user_id);
			one.setTargetUserId(target_user_id);
			one.setIsAuth(1);
			one.setStatus(1);
			one.setCreateTime(SystemClock.now()/1000L);
			one.setUpdateTime(SystemClock.now()/1000L);
			if (one.save()) {
				MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_FAN, target_user_id);
			}	
			renderText("操作成功!");
		} else {
			renderText("已关注了!");
		}
		
			
	}
	
	public void nearby() {
		UsersInfo info = UsersInfo.dao.findFirst("select id,lat,lng from users_info where user_id = " + getPara("user_id"));
		if (info != null) {
			String lat = "31.312204";
			if (!StringUtil.empty(info.getLat())) {
				lat = info.getLat();
			}
			String lng = "120.604485";
			if (!StringUtil.empty(info.getLng())) {
				lng = info.getLng();
			}
			String distance = "ROUND(6378.138 * 2 * ASIN(  SQRT(  POW(  SIN(  (  "
					   + lat + " * PI() / 180 - a.lat * PI() / 180 ) / 2  ),  2 ) + COS("
			           + lat + " * PI() / 180) * COS(a.lat * PI() / 180) * POW( SIN( ( " 
	                + lng + " * PI() / 180 - a.lng * PI() / 180 ) / 2 ), 2 ))) * 1000) ";
			String sql = "select u.nick_name,u.user_mobile,u.user_header,a.user_id," + distance + " as distance,u.login_status,logout_time,u.is_true,a.lat,a.lng,u.sex,u.area_id ";
			String andSql = " from users_info as a left join users u on u.id = a.user_id ";
			andSql += " where a.lat is not null and a.lng is not null and u.is_show_nearby = 1 and u.nick_name is not null and u.status = 1 ";
			andSql += " and u.user_header is not null and LENGTH(u.user_header) > 0 and u.disable_time != -1 and u.disable_time < " + SystemClock.now() /1000;
			andSql += " order by distance limit 100 ";
			List<UsersInfo> infoList = UsersInfo.dao.find(sql + andSql);
			setAttr("list", infoList);
			setAttr("lat", lat);
			setAttr("lng", lng);
			setAttr("user_id", getPara("user_id"));
			
			ArrayList<Area> areaList = CacheKit.get("constant", "arealist", new IDataLoader(){
			       public Object load() {
			           return Area.dao.getIProvince();
			}});
	    	setAttr("area_list", areaList);
	    	Users users = Users.dao.findById(getPara("user_id"));
	    	
	    	setAttr("area_id", users.getAreaId());
	    	
	    	
	    	int day7before = 0;
	    	int day7after = 0;
	    	int newperson = 0; 
	    	for(UsersInfo one : infoList) {
	    		if (!StringUtil.empty(one.getStr("user_mobile")) &&one.getStr("user_mobile").indexOf("88800") > -1) {
	    			newperson ++;
	    		}
	    		if (one.getInt("login_status") == 0 ) {
	    			day7before ++;
	    		} else {
	    			if (one.getLong("logout_time").longValue() > (SystemClock.now()/1000L - 7 * 24 * 60 * 60)) {
	    				day7before ++;
	    			} else {
	    				day7after ++;
	    			}
	    		}
	    		
	    	}
	    	
	    	
	    	UserFans fansCnt = UserFans.dao.findFirst("select count(f.id) as cnt from user_fans as f where f.target_user_id = " + getPara("user_id"));
	    	
	    	setAttr("fans_cnt", fansCnt.get("cnt"));
	    	
	    	setAttr("day7before", day7before);
	    	setAttr("day7after", day7after);
	    	setAttr("newperson", newperson);
	    	
			render("nearby.html");
		} else {
			renderText("数据错误");
		}
			
	}
	
	public void checkList() {
		List<UserCheck> checkList = UserCheck.dao.find("select c.user_id,c.head  from user_check as c LEFT JOIN users as u on c.user_id = u.id where c.`status` = 2 and u.auth_badge < 2 ");
		setAttr("list", checkList);
		render("check_list.html");
	}
	
	public void checkResult() {
		String user_id = getPara("user_id");
		Db.update("update users set auth_badge = 2,sex = " + getPara("sex") + " where  id = " + user_id);
		renderText("操作成功！");
	}
	
	public void introList() {
	   String sql = "select a.id,a.user_id,a.introduction,u.nick_name,ae.name as area_name, FROM_UNIXTIME(u.birthday,'%Y-%m-%d') as birthday_string,u.is_true, CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name,case u.is_true when '2' then 'B类' when '3' then 'C类'  when '4' then 'D类' else 'A类' end as is_true_name  ";
	   sql += ", FROM_UNIXTIME(a.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string,  FROM_UNIXTIME(u.up_time,'%Y-%m-%d %H:%i') as up_time_string  ";
	   String andSql = " from users_info as a left join users u on a.user_id = u.id left join area ae on ae.code = u.area_id where a.introduction is not null and  LENGTH(a.introduction) > 0 and a.introduction != '请输入个性签名' and a.introduction != '火星人' ";
	   if(!StringUtil.empty(getPara("content"))) {
      		andSql += " and (a.introduction like '%" + StringUtil.encode(getPara("content")).replace("%", "\\%") +"%' or a.introduction like '%" + getPara("content")+"%')";
       }
       if(!StringUtil.empty(getPara("user_id"))) {
       		andSql += " and a.user_id = " + getPara("user_id");
       }
       andSql += " order by a.update_time desc ";
       int page = 1;
       if(!StringUtil.empty(getPara("page"))) {
       	  page = getParaToInt("page");
       }
       
       Page<UsersInfo> usersInfoPage = UsersInfo.dao.paginate(page,30, sql, andSql);
       for (UsersInfo users :usersInfoPage.getList() ){
    	   if (users.getIntroduction() != null) {
    		   users.setIntroduction(StringUtil.decode(users.getIntroduction()));
    	   }
	   }
       setAttr("page", usersInfoPage);
       setAttr("content", getPara("content"));
       setAttr("user_id", getPara("user_id"));
       render("intro_list.html");
	}
	
	public void delIntro() {
		Db.update("update users_info set introduction = null where id = " + getPara("id"));
		renderText("操作成功！");
	}
	
	public void delIntroSelect() {
		String[] ids = getPara("ids").split(",");
 		for(String str :ids) {
 			Db.update("update users_info set introduction = null where id = " + str);
 		}
		renderText("操作成功！");
	}


	public void index() {
		
		Users online_1 = Users.dao.findFirst("SELECT count(id ) as cnt from users where is_true = 1 and login_status = 0");
		setAttr("online_cnt_1", online_1.getLong("cnt") * beishu);
		
		
		Users online = Users.dao.findFirst("SELECT count(id ) as cnt from users where is_true > 1 and login_status = 0");
		setAttr("online_cnt", online.getLong("cnt") * beishu);
		

		String sql = "select u.user_mobile,u.id,u.nick_name,u.hot_val,u.login_status,u.logout_time,u.card_tag_ids,u.vip_end_time,u.up_time,u.vip_badpe,info.qq_openid,info.wx_unionid,info.apple_id,ae.name as area_name, FROM_UNIXTIME(u.birthday,'%Y-%m-%d') as birthday_string,u.is_true, CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name,case u.is_true when '2' then 'B类' when '3' then 'C类'  when '4' then 'D类' else 'A类' end as is_true_name  ";
		sql += ", FROM_UNIXTIME(u.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string,  FROM_UNIXTIME(u.up_time,'%Y-%m-%d %H:%i') as up_time_string  ";
		
		String andSql = " from users u  left join users_info as info on info.user_id = u.id left join area ae on ae.code = u.area_id where 1 = 1 ";
		
		if(!StringUtil.empty(getPara("gps"))) {
        	andSql += " and info.lat is null " ;
        }
		/*
		 * left join navy_users as navy on u.id = navy.user_id
		else {
        	andSql = " from users u left join users_info as info on info.user_id = u.id left join area ae on ae.code = u.area_id where 1 = 1 ";
        }
        */
		//是否真实用户
        if(!StringUtil.empty(getPara("is_true"))) {
        	int is_true = getParaToInt("is_true");
        	if (is_true < 100) {
        		andSql += " and u.is_true = " + getPara("is_true");
        	} else {
        		andSql += " and u.is_true = 1 and u.is_gray = 1 ";
        	}
        }
        if(!StringUtil.empty(getPara("user_mobile"))) {
        	andSql += " and u.user_mobile = " + getPara("user_mobile");
        }
        if(!StringUtil.empty(getPara("user_id"))) {
        	andSql += " and u.id = " + getPara("user_id");
        }
        if(!StringUtil.empty(getPara("sex"))) {
        	andSql += " and u.sex = " + getPara("sex");
        }
        if(!StringUtil.empty(getPara("zu"))) {
        	andSql += " and u.zu = '" + getPara("zu") + "' ";
        }
        if (!StringUtil.empty(getPara("minage"))) {
			andSql += " and u.birthday < " +(SystemClock.now()/1000L - getParaToInt("minage") * 365 * 24*60* 60);
        }
		if (!StringUtil.empty(getPara("maxage"))) {
			andSql += " and u.birthday > " +(SystemClock.now()/1000L - getParaToInt("maxage") * 365 * 24*60* 60);
        }
		
        if(!StringUtil.empty(getPara("vip_badpe"))) {
        	andSql += " and u.vip_badpe = " + getPara("vip_badpe");
        }
        if(!StringUtil.empty(getPara("area"))) {
        	andSql += " and u.area_id = " + getPara("area");
        } else {
        	if(!StringUtil.empty(getPara("person"))) {
        		if (!"100".equalsIgnoreCase(getPara("person"))) {
        			andSql += StringUtil.getSQLForPerson(getPara("person"));
        		}
        	}
        }
        if(!StringUtil.empty(getPara("gps"))) {
        	andSql += " and info.lat = null ";
        }
        
        if(!StringUtil.empty(getPara("nick_name"))) {
        	andSql += " and (u.nick_name like '%" + getPara("nick_name") +"%' or u.nick_name like '%" + StringUtil.encode(getPara("nick_name")).replace("%", "\\%")  +"%') ";
        }
        if(StringUtil.empty(getPara("header"))) {
        	
        } else {
        	int header = getParaToInt("header");
        	if (header == 1) {
        		andSql += " and u.user_header is not null and length(u.user_header) > 0  ";
        	} else {
        		andSql += " and (u.user_header is null or length(u.user_header) = 0)  ";
        	}
        }
        andSql += " GROUP BY u.id order by ";
        if(!StringUtil.empty(getPara("pre"))) {
        	andSql += " u.up_time desc,";
        }
        andSql += "  u.id desc ";
        int page = 1;
        if(!StringUtil.empty(getPara("page"))) {
        	page = getParaToInt("page");
        } 
        Page<Users> usersPage = Users.dao.paginate(page, 30, sql, andSql);
        for (Users users :usersPage.getList() ){
//	 		users.setUserHeader(users.getUserHeader() + PicUtil.QINIU_CUT_ADMIN);
        	if (users.getNickName() != null) {
        		users.setNickName(StringUtil.decode(users.getNickName()));
        	}
        	if (users.getLoginStatus() != 0) {
        		users.setCardTagIds(DateUtil.cul(users.getLong("logout_time")));
        	}
	 	}
        ArrayList<Area> areaList = CacheKit.get("constant", "arealist", new IDataLoader(){
		       public Object load() {
		           return Area.dao.getIProvince();
		}});
        setAttr("area_list", areaList);
        setAttr("page", usersPage);
        setAttr("user_mobile", getPara("user_mobile"));
        setAttr("user_id", getPara("user_id"));
        setAttr("is_true", getPara("is_true"));
        setAttr("zu", getPara("zu"));
        setAttr("sex", getPara("sex"));
        setAttr("area", getPara("area"));
        setAttr("header", getPara("header"));
        setAttr("pre", getPara("pre"));
        setAttr("gps", getPara("gps"));
        setAttr("nick_name", getPara("nick_name"));
        setAttr("vip_badpe", getPara("vip_badpe"));
        setAttr("minage", getPara("minage"));
        setAttr("maxage", getPara("maxage"));
        
        String person = getPara("person");
        if(StringUtil.empty(person)) {
        	 person = CookiesUtil.getName(getRequest(), "person");
        } else {
        	if ("100".equals(person)) {
        		CookiesUtil.add(getResponse(), "person", "0");
        	} else {
        		CookiesUtil.add(getResponse(), "person", person);
        	}
        	
        }
        setAttr("person", person);
        render("index.html");
	}
	
	public void detail() {
		int user_id = getParaToInt("user_id");
		Users users = Users.dao.findFirst("select a.*,FROM_UNIXTIME(a.birthday,'%Y-%m-%d') as birthday_string,FROM_UNIXTIME(a.talk_end_time,'%Y-%m-%d') as talk_end_time_string,ui.lng,ui.lat,ui.lng_A,ui.lat_A,ui.introduction,ui.weight,ui.height from users as a left join users_info ui on ui.user_id = a.id where a.id = " + user_id);
	 	if (users != null ){
        	if (users.getNickName() != null) {
        		users.setNickName(StringUtil.decode(users.getNickName()));
        	}
	 	}
		setAttr("users", users);
		ArrayList<Area> areaList = CacheKit.get("constant", "arealist", new IDataLoader(){
		       public Object load() {
		           return Area.dao.getIProvince();
		       }
		});
		
		ArrayList<Tags> tagsList = CacheKit.get("constant", "tagsList", new IDataLoader(){
		       public Object load() {
		           return Tags.dao.getAll();
		       }});
		
		ArrayList<Tags> prv_tags_list = CacheKit.get("constant", "prv_tagsList", new IDataLoader(){
		       public Object load() {
		           return Tags.dao.getPrv();
		}});
	 	setAttr("area_list", areaList);
	 	setAttr("tags_list", tagsList);
	 	 
	 	setAttr("prv_tags_list", prv_tags_list);
	 	
	 	List<UserAlbums> albumsList = UserAlbums.dao.find("select * from user_albums where status = 1 and user_id = " + user_id);
	 	setAttr("albums_list", albumsList);
	 	
	 	String sql = "select h.id,h.user_id,h.content, FROM_UNIXTIME(h.create_time,'%Y-%m-%d %H:%i') as create_time_string,hot,u.nick_name ";
        String andSql = " from user_hellos as h left join users as u on h.user_id = u.id where h.`status` = 2 and h.delete_time is null and h.today_time > 0 and h.create_time > " + (SystemClock.now()/1000L - 10 *24*3600L) + " and  h.target_user_id = " + user_id ;
        
        List<UserHellos> hellos = UserHellos.dao.find(sql + andSql);
	 	setAttr("hellos", hellos);
		render("detail.html");
	}
	
	public void deleteAlbums() {
		UserAlbums user_albums = UserAlbums.dao.findById(getPara("id"));
		new PicUtil().delete(user_albums.getImg());
		Db.delete("delete from user_albums where id = " + getPara("id"));
		renderText("操作成功！");
	}
	
	public void addAlbums() {
		UserAlbums one = new UserAlbums();
		one.setUserId(getParaToInt("user_id"));
		one.setImg(getPara("img"));
		one.setStatus(1);
		one.setImgCheck(1);
		one.setCreateTime(SystemClock.now()/1000L);
		one.save();
		renderText("操作成功！");
	}
	
	public void save() {
		int user_id = getParaToInt("user_id");
		Users one = Users.dao.findById(user_id);
		if(one != null) {
			if (! StringUtil.empty(getPara("nick_name"))) {
				one.setNickName(StringUtil.encode(getPara("nick_name")));
			}
			if (! StringUtil.empty(getPara("user_password"))) {
				one.setUserPassword(Users.password(getPara("user_password")));
			}
			if (! StringUtil.empty(getPara("user_header"))) {
				one.setUserHeader(getPara("user_header"));
			}
			if (!StringUtil.empty(getPara("birthday"))) {
				try {
					one.setBirthday(DateUtil.commonDateFormat.parse(getPara("birthday")).getTime()/1000L);
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			if (!StringUtil.empty(getPara("talk_end_time"))) {
				try {
					one.set("talk_end_time",DateUtil.commonDateFormat.parse(getPara("talk_end_time")).getTime()/1000L);
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			one.setTagIds(getPara("tag_ids"));
			one.set("private_tag_ids", getPara("private_tag_ids"));
			one.setSex(getParaToInt("sex"));
			one.setUserMobile(getPara("user_mobile"));
			one.setAreaId(getParaToLong("area_id"));
			int is_true = getParaToInt("is_true");
			one.setIsTrue(is_true);
			one.setStatus(getParaToInt("status"));
			one.setIsRealName(getParaToInt("is_real_name"));
			one.setIsGray(getParaToInt("is_gray"));
			one.set("zu",getPara("zu"));
			if (!StringUtil.empty(getPara("auth_badge"))) {
				one.set("auth_badge",getParaToInt("auth_badge"));	
			}
			one.set("talk_badge",getParaToInt("talk_badge"));
			one.setIsTrue(is_true);
			if (StringUtil.empty(one.getUserHeader())) {
				one.setUserHeader("head3.png");
			}
			one.update();
			Db.update("update users_info set lng ='"+ getPara("lng") +"', lat='" + getPara("lat") + "',weight ="+getPara("weight")+",height = "+getPara("height")+" where user_id = " + user_id);
			if (is_true == 2 && !StringUtil.empty(getPara("lng_A")) && !StringUtil.empty(getPara("lat_A"))) {
				Db.update("update users_info set lng_A ='"+ getPara("lng_A") +"', lat_A ='" + getPara("lat_A") + "' where user_id = " + user_id);	
			}
			if (!StringUtil.empty(getPara("introduction"))) {
				Db.update("update users_info set introduction ='"+StringUtil.encode(getPara("introduction"))+"' where user_id = " + user_id);
			}
			
			try {
				RongCloudUtil.update(one);
			} catch (Exception e) {
			}
			
		}
		renderText("操作成功!");
	}
	
	
	//是否置顶
    public void status(){
    	Db.update("UPDATE users SET status = ( CASE `status`  WHEN 1 THEN 2   WHEN 2 THEN 1 END ) where id =" +getPara("id"));
        renderText("操作成功!");
    }
    
    public void hot_pro() {
    	//vip_end_time
    	if (!StringUtil.empty(getPara("vip_end_time"))) {
    		try {
				Long vip_end_time = DateUtil.commonDateFormat.parse(getPara("vip_end_time")).getTime() /1000L;
				Db.update("UPDATE users SET vip_end_time = " + vip_end_time +" where id = " + getPara("id"));
			} catch (ParseException e) {
				e.printStackTrace();
			}
    	} 
    	if (!StringUtil.empty(getPara("hot_val"))) {
    		Db.update("UPDATE users SET hot_val = " + getPara("hot_val") + " where id = " + getPara("id"));
    	}
    	if (!StringUtil.empty(getPara("vip_badpe"))) {
    		Db.update("UPDATE users SET vip_badpe = " + getPara("vip_badpe") + " where id = " + getPara("id"));
    	}
    	
    	renderText("操作成功!");
    }
    
    public void disable() {
    	int disable_time = getParaToInt("disable_time");
    	if (disable_time == -1 ) {
    		Db.update("UPDATE users SET disable_time = -1 where id = " + getPara("id"));
    	} else {
    		long time = SystemClock.now() / 1000 + disable_time*24*60*60;
    		Db.update("UPDATE users SET disable_time = "+ time + "  where id = " + getPara("id"));
    	}
    	renderText("操作成功!");
    }
    
    public void forbid() {
    	Db.update("UPDATE users SET forbid_time = " + (SystemClock.now()/1000 + 1 * 24 * 3600 ) +  " where id = " + getPara("id"));
    	renderText("操作成功!");
    }
    
    
    public void pack() {
    	setAttr("user_id", getPara("user_id"));
    	JSONObject packageData = new JSONObject();
    	packageData.put("1", VipPackage.dao.find("select id ,title ,type from vip_package where status =1 and delete_time is null and type = 1 order by sort desc " ));
    	packageData.put("2", VipPackage.dao.find("select id ,title ,type from vip_package where status =1 and delete_time is null and type = 2 order by sort desc " ));
    	setAttr("packageData", packageData);
    	render("pack.html");
    }
    
    public void add_pack() {
    	String user_id = getPara("user_id");
    	Users users = Users.dao.findFirst("select * from users where id = " + user_id +" or user_mobile = '"+ user_id +"'");
    	
    	if(users != null) {
    		VipPackage packOne = VipPackage.dao.findById(getPara("pack_id"));
    		VipRecord one = new VipRecord();
    		if(packOne.getType() == 1) {
        		one.setUserId(users.getId().intValue());
        		one.setOrderNum(Toolkit.newTradeNo());
        		one.setTitle(packOne.getTitle() + "(系统赠送)");
        		one.setZsHot(packOne.getZsHot());
        		one.setTime(Integer.valueOf(packOne.getDays()));
        		one.setStatus(2);
        		one.setVipPackageId(packOne.getId());
        		one.setOrderType(1);
        		one.setPrice(packOne.getPrice());
        		one.setCreateTime(SystemClock.now()/1000L);
        		one.setUpdateTime(SystemClock.now()/1000L);
        		one.save();
        		int zs_hot = packOne.getZsHot();
				long time = one.getTime() * 86400L;
				if (users.getVipEndTime() == null || users.getVipEndTime() == 0L  || users.getVipEndTime() < (SystemClock.now() /1000L)) {
					time = SystemClock.now() /1000L + time;
				} else {
					time = users.getVipEndTime() + time;
				}
				Db.update("update users set vip_end_time = " + time +",hot_val = hot_val+ "+ zs_hot +" where id = " + user_id);
				
        		if (one.getPrice().intValue() == 98) {
					Db.update("update users set vip_badpe = 1 where id = " + user_id);	
				} else if (one.getPrice().intValue() == 198) {
					Db.update("update users set vip_badpe = 2 where id = " + user_id);
				} else if (one.getPrice().intValue() == 298) {
					Db.update("update users set vip_badpe = 3 where id = " + user_id);
				} else if (one.getPrice().intValue() == 298) {
					Db.update("update users set vip_badpe = 3 where id = " + user_id);
				} else if (one.getPrice().intValue() > 900) {
					Db.update("update users set vip_badpe = 4 where id = " + user_id);
				}
    		} else {
        		one.setUserId(users.getId().intValue());
        		one.setOrderNum(Toolkit.newTradeNo());
        		one.setTitle("热度充值"+ packOne.getHot() + "℃(系统赠送)");
        		one.setHot(packOne.getHot());
        		one.setZsHot(packOne.getZsHot());
        		one.setTime(0);
        		one.setStatus(2);
        		one.setVipPackageId(packOne.getId());
        		one.setOrderType(2);
        		one.setPrice(packOne.getPrice());
        		one.setCreateTime(SystemClock.now()/1000L);
        		one.setUpdateTime(SystemClock.now()/1000L);
        		one.save();
    		}
    		boolean result = OrderService.one.record(one,"System");
    		if(result) {
    			renderText("操作成功!");
    			return ;
    		}
    	}
    	
    	renderText("操作成功!");
    }
    
    public void wrapList() {
    	List<TempWrap> list = TempWrap.dao.find("select *,FROM_UNIXTIME(create_time,'%Y-%m-%d %H:%i') as create_time_string from temp_wrap order by id asc ");
    	setAttr("list", list);
    	render("wrap_list.html");
    }
    
    public void wrapDelete() {
    	Db.delete("delete from temp_wrap where id = "+ getPara("id"));
    	renderText("操作成功!");
    }
    
    public void user_name(){
        Users users = Users.dao.findById(getPara("user_id"));
        String user_name = "";
        if(!StringUtil.empty(users.getNickName())){
            user_name = StringUtil.decode(users.getNickName());
        }else{
            user_name = "火星人";
        }
        if(users.getVipEndTime() != null && users.getVipEndTime() > (SystemClock.now()/1000L)){
            user_name = user_name + "(会员)";
        }
        Map<String, Object> result = Maps.newHashMap();
        result.put("user_name", user_name);
        renderText(APIJSON.send(result));
    }

    public void user_head(){
    	Users users = Users.dao.findById(getPara("user_id"));
        String user_header = "";
        if(!StringUtil.empty(users.getUserHeader())){
        	 user_header = PicUtil.QINIU_DIR +  StringUtil.decode(users.getUserHeader());
        }else{
        	 user_header = PicUtil.DEFAULT_HEAD;
        }
        Map<String, Object> result = Maps.newHashMap();
        result.put("user_header", user_header);
        renderText(APIJSON.send(result));
    }
   
    public void zu_location() {
    	List<Users> zu_list = Users.dao.find("select zu,user_name from users where zu is not null and LENGTH(zu) > 0 group by zu ");
    	setAttr("list", zu_list);
    	render("zu_location.html");
    }
 
    /**
     * 切换AB点  
     */
    public void qiehuan_zu() {
    	String zu = getPara("zu");
    	List<UsersInfo> list = UsersInfo.dao.find("select i.id,i.user_id,i.lng,i.lat,i.lng_A,i.lat_A from users_info as i left join users as u on i.user_id = u.id where u.zu = '"+ zu +"'");
    	if (list != null && list.size() > 0) {
    		Db.update("UPDATE users SET user_name = ( CASE `user_name`  WHEN 'A' THEN 'B'   WHEN 'B' THEN 'A' END ) where zu ='" +zu+"'");	
    	}
    	for(UsersInfo one :list) {
        	try {
        		String lng = one.getLng();
            	String lat = one.getLat();
            	String lng_A = one.getStr("lng_A");
            	String lat_A = one.getStr("lat_A");
//            	int user_id = one.getUserId();
            	if (!StringUtil.empty(lng) && !StringUtil.empty(lat) && !StringUtil.empty(lng_A) && !StringUtil.empty(lat_A) ) {
            		Db.update("update users_info set lng = '"+ lng_A +"' , lat ='" + lat_A +"',lat_A = '" + lat +"',lng_A ='"+ lng +"' where id = " + one.getId());
    				Thread.sleep(2000);
            	}
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
    	renderText("OK");
    }
    
    
 // 关注
 	@Before(AdminInterceptor.class)
 	public void giveFollow2(){
 		int num  = 1 + new Random().nextInt(5);
 	    String sql = "select id from users where is_true > 1 and sex = 1 order by  RAND()  limit  " + num;
 	    List<Users> users = Users.dao.find(sql);
 	    for(Users u : users) {
 	    	Long user_id = u.getId(); 
 	    	int target_user_id = getParaToInt("user_id");
 	    	
 			UserSees one1 = new UserSees();
 			one1.setUserId(user_id.intValue());
 			one1.setTargetUserId(target_user_id);
 			one1.setCreateTime(SystemClock.now()/1000L - 1 * 60);
 			one1.setUpdateTime(SystemClock.now()/1000L);
 			if (one1.save()) {
 				new CardController().giveABPoint(user_id.intValue());
 				MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_SEE, target_user_id);
 			}
 	    	//判断是否关注
 			UserFans one = UserFans.dao.findFirst("select id , user_id from user_fans where user_id = " + user_id+ " and target_user_id = " + target_user_id +" and delete_time is null ");
 			if (one == null) {
 				one = new UserFans();
 				one.setUserId(user_id.intValue());
 				one.setTargetUserId(target_user_id);
 				one.setIsAuth(1);
 				one.setStatus(1);
 				one.setCreateTime(SystemClock.now()/1000L);
 				one.setUpdateTime(SystemClock.now()/1000L);
 				if (one.save()) {
 					new CardController().giveABPoint(user_id.intValue());
 					MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_FAN, target_user_id);
 				}	
 			} 
 	    }
 	    renderText("操作成功!  已加 " + num +"个关注");
 	}
 	
 	@Before(AdminInterceptor.class)
 	public void giveFollow3(){
 		String[] ids = getPara("ids").split(",");
 		for(String str :ids) {
 			int num  = 1 + new Random().nextInt(5);
 	 	    String sql = " SELECT t1.id FROM `users` AS t1 JOIN (SELECT ROUND(RAND() * (SELECT MAX(id) FROM `users`)) AS id) AS t2 WHERE t1.id >= t2.id and is_true > 1 and sex = 1 ORDER BY t1.id ASC LIMIT " + num;
 	 	    List<Users> users = Users.dao.find(sql);
 	 	    for(Users u : users) {
 	 	    	Long user_id = u.getId(); 
 	 	    	int target_user_id = Integer.valueOf(str);
 	 	    	UserSees one1 = new UserSees();
 	 			one1.setUserId(user_id.intValue());
 	 			one1.setTargetUserId(target_user_id);
 	 			one1.setCreateTime(SystemClock.now()/1000L - 1 * 60);
 	 			one1.setUpdateTime(SystemClock.now()/1000L);
 	 			if (one1.save()) {
 	 				new CardController().giveABPoint(user_id.intValue());
 	 				MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_SEE, target_user_id);
 	 			}
 	 	    	//判断是否关注
 	 			UserFans one = UserFans.dao.findFirst("select id , user_id from user_fans where user_id = " + user_id+ " and target_user_id = " + target_user_id +" and delete_time is null ");
 	 			if (one == null) {
 	 				one = new UserFans();
 	 				one.setUserId(user_id.intValue());
 	 				one.setTargetUserId(target_user_id);
 	 				one.setIsAuth(1);
 	 				one.setStatus(1);
 	 				one.setCreateTime(SystemClock.now()/1000L);
 	 				one.setUpdateTime(SystemClock.now()/1000L);
 	 				if (one.save()) {
 	 					new CardController().giveABPoint(user_id.intValue());
 	 					MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_FAN, target_user_id);
 	 				}	
 	 			} 
 	 	    }
 		}
 	    renderText("操作成功!");
 	}
 	

 	@Before(AdminInterceptor.class)
 	public void giveMessage(){
 		String[] ids = getPara("ids").split(",");
 		for(String str :ids) {
 	    	int target_user_id = Integer.valueOf(str);
 	    	Users users = Users.dao.findById(target_user_id);
 	    	if (users.getInt("vip_badpe") == 0) {
 	    		MessageUnreadNum.dao.addNum(MessageUnreadNum.MESSAGE_UNREAD_TYPE_SEE, target_user_id);
 	    	}
 		}
 	    renderText("操作成功!");
 	}
 	
    
    public void move_gps() {
    	String loc = getPara("gps");
    	double distance = getParaToInt("distance") * 1000.0;
    	int sex = getParaToInt("sex");
    	String area_id = getPara("area_id");
    	
    	List<UsersInfo> info_list = UsersInfo.dao.find("select f.id,f.user_id from users_info as f left join users as u on u.id = f.user_id where u.is_true = 3 and u.user_header is not null and length(u.user_header) > 0 and sex = " + sex + " and (lat is null or lat ='4.9E-324') order by RAND() desc limit " + getPara("limit"));
    	for(UsersInfo one :info_list) {
    		String gps =  Toolkit.getRandGPS(new Double(loc.split(",")[0]), new Double(loc.split(",")[1]), distance);
    		String new_lat = gps.split(",")[0];
    		String new_lng = gps.split(",")[1];
    		// 没位置设置A点
    		Db.update("update users_info set lat = " + new_lat +",lng =" + new_lng +" where user_id= " + one.getUserId());
    		Db.update("update users set area_id = " + area_id + " where id = " + one.getUserId());
    		new CardController().giveABPoint(one.getUserId());
    		System.out.println("move id = " + one.getUserId());
    	}
    	renderText("操作成功!");
    }
    
    /**
     * 指定user_id
     */
    public void move_gps_2() {
    	String[] ids = getPara("ids").split(",");
 		for(String str :ids) {
 			Users users = Users.dao.findById(str);
 			UsersInfo users_info = UsersInfo.dao.findFirst("select * from users_info where user_id = " + str);
 	    	double distance = 20000.0;
 	    	int sex = 2;
 	    	if(users_info.getLat() != null && users_info.getLng() != null ) {
 	    		List<UsersInfo> info_list = UsersInfo.dao.find("select f.id,f.user_id from users_info as f left join users as u on u.id = f.user_id where u.is_true = 3 and u.user_header is not null and length(u.user_header) > 0 and sex = " + sex + " and (lat is null or lat ='4.9E-324') order by RAND() desc limit 2 ");
 	 	    	for(UsersInfo one :info_list) {
 	 	    		String gps =  Toolkit.getRandGPS(new Double(users_info.getLat()), new Double(users_info.getLng()), distance);
 	 	    		String new_lat = gps.split(",")[0];
 	 	    		String new_lng = gps.split(",")[1];
 	 	    		// 没位置设置A点
 	 	    		Db.update("update users_info set lat = " + new_lat +",lng =" + new_lng +" where user_id= " + one.getUserId());
 	 	    		Db.update("update users set area_id = " + users.getAreaId() + " where id = " + one.getUserId());
 	 	    		new CardController().giveABPoint(one.getUserId());
 	 	    		System.out.println("move id = " + one.getUserId());
 	 	    	}
 	    	}
 	    	
 		}	
    	
    	renderText("操作成功!");
    }
    
    @Before(AdminInterceptor.class)
 	public void giveNickNameRule(){
    	String[] ids = getPara("ids").split(",");
 		for(String str :ids) {
 			Db.update("update users set nick_name='昵称违规' where id = " + str);
 		}
 	    renderText("操作成功!");
 	}
    
    public void getTypeForId() {
    	String msg = "A类";
    	Users users = Users.dao.findById(getPara("user_id"));
    	if (users.getIsTrue() == 1) {
    		
    	} else {
    		if (!StringUtil.empty(users.getUserMobile()) ) {
    			if (users.getUserMobile().startsWith("88800")) {
    				msg = "C类";
    			} else {
    				NavyUsers navy_users = NavyUsers.dao.findFirst("select id from navy_users where user_id = " + users.getId());
    				if (navy_users != null) {
    					msg = "B类";
    				} else {
    					msg = "D类";
    				}
    			}
    		} else {
    			NavyUsers navy_users = NavyUsers.dao.findFirst("select id from navy_users where user_id = " + users.getId());
    			if (navy_users != null) {
					msg = "B类";
				} else {
					msg = "D类";
				}
    		}
    	} 
    	renderText(msg);
    }
    
}
